﻿using AccessControl.Entity;
using EMIS.Entity;
using EMIS.Http;
using MQTTnet;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Media;
using KV_WSN;
using KV_WSN.Sensor;
using SmartShopping;
using Timer = System.Timers.Timer;

namespace EMIS
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 设备控制主题
        /// </summary>
        public const string DeviceControlTopic = "$kvc";

        public const int ReadEnvironmentInfoInterval = 2 * 1000;

        private Timer _clockTimer;

        private Timer _timer;

        private Timer _autoFlashLightTimer = new Timer();

        private bool _lightFlag = false;

        private bool _fengshanFlag = false;

        private bool _lockFlag = false;


        public MainWindow()
        {
            InitializeComponent();
            //启动配置界面
            WinConfig win = new WinConfig();
            if (win.ShowDialog() == true)
            {
                Console.WriteLine();
            }
            else
            {
                Close();
                Environment.Exit(0);
            }

            //别动这行代码
            Thread.Sleep(500);
        }

        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            #region 日期时间

            _clockTimer = new Timer();
            _clockTimer.AutoReset = true;
            _clockTimer.Interval = 1 * 1000;
            _clockTimer.Elapsed += (o, args) =>
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    DateTime dt = DateTime.Now;
                    txtTime.Text = dt.ToString("T");
                    txtDate.Text = $"{dt:yyyy/MM/dd}";
                    txtWeek.Text = GetWeekStr(dt.DayOfWeek);
                }));
            };
            _clockTimer.Enabled = true;

            #endregion

            _timer_Elapsed(null, null);

            _timer = new Timer();
            _timer.Interval = ReadEnvironmentInfoInterval;
            _timer.AutoReset = true;
            _timer.Elapsed += (o, args) => { Dispatcher.Invoke(new Action(() => { _timer_Elapsed(null, null); })); };
            _timer.Enabled = true;

            #region 灯闪烁

            _autoFlashLightTimer.AutoReset = true;
            _autoFlashLightTimer.Elapsed += (o, args) =>
            {
                if (_lightFlag == false)
                {
                    LightOperation(_lightFlag);
                    _lightFlag = true;
                }
                else if (_lightFlag == true)
                {
                    LightOperation(_lightFlag);
                    _lightFlag = false;
                }
            };

            #endregion

            #region 检测传感器设备

            if (Global.isOpen)
            {
                if (Global.smoke.Data != null)
                {
                    //开始检测是否有火焰烟雾
                    Thread tSmoke = new Thread(new ThreadStart(CheckSmoke));
                    tSmoke.IsBackground = true;
                    tSmoke.Start();
                }
                else
                {
                    MessageBox.Show("未获取到设备（烟雾传感器）,请检查设备是否连接正确，并重新启动程序");
                    Close();
                }

                if (Global.Infrared.Data != null)
                {
                    //开始检测是否有人
                    Thread tInfared = new Thread(new ThreadStart(CheckInfared))
                    {
                        IsBackground = true
                    };
                    tInfared.Start();
                }
                else
                {
                    MessageBox.Show("未获取到设备（人体红外传感器）,请检查设备是否连接正确，并重新启动程序");
                    Close();
                }
            }
            else
            {
                MessageBox.Show("串口打开失败");
            }

            #endregion
        }


        /// <summary>
        /// 获取周次
        /// </summary>
        /// <param name="week"></param>
        /// <returns></returns>
        private string GetWeekStr(DayOfWeek week)
        {
            string result = "";
            switch (week)
            {
                case DayOfWeek.Sunday:
                    result = "星期日";
                    break;
                case DayOfWeek.Monday:
                    result = "星期一";

                    break;
                case DayOfWeek.Tuesday:
                    result = "星期二";

                    break;
                case DayOfWeek.Wednesday:
                    result = "星期三";

                    break;
                case DayOfWeek.Thursday:
                    result = "星期四";

                    break;
                case DayOfWeek.Friday:
                    result = "星期五";

                    break;
                case DayOfWeek.Saturday:
                    result = "星期六";
                    break;
            }

            return result;
        }

        private void MainWindow_OnClosed(object sender, EventArgs e)
        {
            if (_clockTimer != null) _clockTimer.Enabled = false;
            if (_timer != null) _timer.Enabled = false;
            if (!Global.coordinator.CloseSerialPort())
            {
                MessageBox.Show("串口关闭失败");
            }

            LightOperation(false);
            FanOperation(false);
            LockOperation(false);
        }


        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            // 获取服务器最新环境数据
            Dictionary<string, string> datas = new Dictionary<string, string>();
            datas.Add("deviceId", MainClass.GatewayId.ToString());
            var responseResult = HttpHelper.Get(MainClass.GetApiConnection(), HttpHelper.GetEnvironmentData, datas);
            if (responseResult.Code == ResponseCode.Success)
            {
                List<EnvironmentDataEntity> environmentDataEntities =
                    JsonConvert.DeserializeObject<List<EnvironmentDataEntity>>(responseResult.Data.ToString());
                if (environmentDataEntities.Count != 2)
                {
                    MessageBox.Show("数据无法完整获取，请检查数据标识是否配置正确。");
                }
                else
                {
                    foreach (var entity in environmentDataEntities)
                    {
                        if (entity.Unit == "摄氏度")
                        {
                            txtTemp.Text = entity.Value.ToString("f1") +
                                           entity.Unit;
                        }
                        else if (entity.Unit == "%rh")
                        {
                            txtHum.Text = entity.Value.ToString("f1") +
                                          entity.Unit;
                            HumJudge(entity.Value.ToString("f1"));
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("服务器错误，请检查网关ID和服务地址是否正确！");
            }
        }


        /// <summary>
        /// 湿度逻辑判断
        /// </summary>
        /// <param name="temp"></param>
        private void HumJudge(string hum)
        {
            if (Convert.ToDouble(hum) >= 35)
            {
                _fengshanFlag = true;
                FanOperation(_fengshanFlag);
                txtFanStaus.Text = "开";
            }
            else if (Convert.ToDouble(hum) < 30)
            {
                _fengshanFlag = false;
                FanOperation(_fengshanFlag);
                txtFanStaus.Text = "关";
            }
        }


        /// <summary>
        /// 灯操作
        /// </summary>
        /// <param name="isOpen"></param>
        private void LightOperation(bool isOpen)
        {
            DeviceOperation(MainClass.LightPortName, isOpen);
        }

        /// <summary>
        /// 风扇操作
        /// </summary>
        /// <param name="isOpen"></param>
        private void FanOperation(bool isOpen)
        {
            DeviceOperation(MainClass.FanName, isOpen);
        }

        /// <summary>
        /// 锁操作
        /// </summary>
        /// <param name="isOpen"></param>
        private void LockOperation(bool isOpen)
        {
            DeviceOperation(MainClass.LockName, isOpen);
        }

        /// <summary>
        /// 设备操作
        /// </summary>
        /// <param name="tag">设备标识</param>
        /// <param name="value">设置值</param>
        private void DeviceOperation(string tag, bool value)
        {
            DeviceControlEntity dc = new DeviceControlEntity();
            DeviceValueEntity dv = new DeviceValueEntity();
            dv.tag = tag;
            dv.value = value ? 1 : 0;
            dc.w.Add(dv);
            MqttApplicationMessage msg = new MqttApplicationMessage();
            msg.Topic = DeviceControlTopic;
            msg.Payload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dc));
            MainClass.MqttClient.PublishAsync(msg, CancellationToken.None);
        }


        #region Zigbee

        /// <summary>
        /// 检测是否有烟雾，有烟雾闪烁灯，上传一条报警信息
        /// </summary>
        public void CheckSmoke()
        {
            while (true)
            {
                if (Global.smoke.Data[0] == 0x01)
                {
                    //上传报警信息

                    Dispatcher.Invoke(new Action(() =>
                    {
                        txtSmokeStaus.Text = "发生火灾";
                        txtDengStaus.Text = "闪烁";
                        txtSmokeStaus.Foreground = new SolidColorBrush(Colors.Red);
                    }));
                    //有烟雾每隔1秒闪烁一次
                    _autoFlashLightTimer.Interval = 1000;
                    _autoFlashLightTimer.Enabled = true;
                    _lightFlag = true;
                    ResponseResult response = new ResponseResult();
                    Dictionary<string, string> datas = new Dictionary<string, string>();
                    datas.Add("warning", "发生火灾，赶快报警");
                    response = HttpHelper.Get(MainClass.GetApiConnection(), HttpHelper.InsertWarning, datas);
                    if (response.Code != ResponseCode.Success)
                    {
                        _ = MessageBox.Show("信息保存失败！！！");
                    }
                }
                else
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        txtSmokeStaus.Text = "正常";
                        txtDengStaus.Text = "关";
                        txtSmokeStaus.Foreground = new SolidColorBrush(Colors.Black);
                    }));
                    _autoFlashLightTimer.Enabled = false;
                    LightOperation(false);
                    _lightFlag = false;
                    _autoFlashLightTimer.Stop();
                }

                Global.coordinator.Ping();
                Thread.Sleep(2000);
            }
        }

        /// <summary>
        /// 检测是否有人，有人打开电子锁
        /// </summary>
        public void CheckInfared()
        {
            while (true)
            {
                int flag = 10;
                if (Global.Infrared.Data[0] == 0x01)
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        txtHongWaiStaus.Text = "有人";
                        txtLockStaus.Text = "开";
                    }));
                    if (!_lockFlag)
                    {
                        _lockFlag = true;
                        LockOperation(_lockFlag);
                    }
                }
                else
                {
                    Dispatcher.Invoke(new Action(() => { txtHongWaiStaus.Text = "无人"; }));

                    if (_lockFlag)
                    {
                        while (flag > 0)
                        {
                            Thread.Sleep(1000);
                            flag--;
                            if (Global.Infrared.Data[0] == 0x01)
                            {
                                return;
                            }
                        }
                        _lockFlag = false;

                        Dispatcher.Invoke(new Action(() => { txtLockStaus.Text = "关"; }));
                        LockOperation(_lockFlag);
                    }

                }

                Global.coordinator.Ping();
            }
        }

        #endregion
    }
}